{
 "cells": [
  {
   "cell_type": "markdown",
   "id": "google",
   "metadata": {},
   "source": [
    "##### Copyright 2025 Google LLC."
   ]
  },
  {
   "cell_type": "markdown",
   "id": "apache",
   "metadata": {},
   "source": [
    "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
    "you may not use this file except in compliance with the License.\n",
    "You may obtain a copy of the License at\n",
    "\n",
    "    http://www.apache.org/licenses/LICENSE-2.0\n",
    "\n",
    "Unless required by applicable law or agreed to in writing, software\n",
    "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
    "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
    "See the License for the specific language governing permissions and\n",
    "limitations under the License.\n"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "basename",
   "metadata": {},
   "source": [
    "# magic_square_mip"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "link",
   "metadata": {},
   "source": [
    "<table align=\"left\">\n",
    "<td>\n",
    "<a href=\"https://colab.research.google.com/github/google/or-tools/blob/main/examples/notebook/contrib/magic_square_mip.ipynb\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/colab_32px.png\"/>Run in Google Colab</a>\n",
    "</td>\n",
    "<td>\n",
    "<a href=\"https://github.com/google/or-tools/blob/main/examples/contrib/magic_square_mip.py\"><img src=\"https://raw.githubusercontent.com/google/or-tools/main/tools/github_32px.png\"/>View source on GitHub</a>\n",
    "</td>\n",
    "</table>"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "doc",
   "metadata": {},
   "source": [
    "First, you must install [ortools](https://pypi.org/project/ortools/) package in this colab."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "install",
   "metadata": {},
   "outputs": [],
   "source": [
    "%pip install ortools"
   ]
  },
  {
   "cell_type": "markdown",
   "id": "description",
   "metadata": {},
   "source": [
    "\n",
    "\n",
    "  Magic square (integer programming) in Google or-tools.\n",
    "\n",
    "  Translated from GLPK:s example magic.mod\n",
    "  '''\n",
    "  MAGIC, Magic Square\n",
    "\n",
    "  Written in GNU MathProg by Andrew Makhorin <mao@mai2.rcnet.ru>\n",
    "\n",
    "  In recreational mathematics, a magic square of order n is an\n",
    "  arrangement of n^2 numbers, usually distinct integers, in a square,\n",
    "  such that n numbers in all rows, all columns, and both diagonals sum\n",
    "  to the same constant. A normal magic square contains the integers\n",
    "  from 1 to n^2.\n",
    "\n",
    "  (From Wikipedia, the free encyclopedia.)\n",
    "  '''\n",
    "\n",
    "  Compare to the CP version:\n",
    "     http://www.hakank.org/google_or_tools/magic_square.py\n",
    "\n",
    "  Here we also experiment with how long it takes when\n",
    "  using an output_matrix (much longer).\n",
    "\n",
    "\n",
    "  This model was created by Hakan Kjellerstrand (hakank@gmail.com)\n",
    "  Also see my other Google CP Solver models:\n",
    "  http://www.hakank.org/google_or_tools/\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "code",
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "from ortools.linear_solver import pywraplp\n",
    "\n",
    "#\n",
    "# main(n, use_output_matrix)\n",
    "#   n: size of matrix\n",
    "#   use_output_matrix: use the output_matrix\n",
    "#\n",
    "\n",
    "\n",
    "def main(n=3, sol='CBC', use_output_matrix=0):\n",
    "  # Create the solver.\n",
    "  print('Solver: ', sol)\n",
    "  solver = pywraplp.Solver.CreateSolver(sol)\n",
    "  if not solver:\n",
    "    return\n",
    "\n",
    "  #\n",
    "  # data\n",
    "  #\n",
    "  print('n = ', n)\n",
    "\n",
    "  # range_n = range(1, n+1)\n",
    "  range_n = list(range(0, n))\n",
    "\n",
    "  N = n * n\n",
    "  range_N = list(range(1, N + 1))\n",
    "\n",
    "  #\n",
    "  # variables\n",
    "  #\n",
    "\n",
    "  # x[i,j,k] = 1 means that cell (i,j) contains integer k\n",
    "  x = {}\n",
    "  for i in range_n:\n",
    "    for j in range_n:\n",
    "      for k in range_N:\n",
    "        x[i, j, k] = solver.IntVar(0, 1, 'x[%i,%i,%i]' % (i, j, k))\n",
    "\n",
    "  # For output. Much slower....\n",
    "  if use_output_matrix == 1:\n",
    "    print('Using an output matrix')\n",
    "    square = {}\n",
    "    for i in range_n:\n",
    "      for j in range_n:\n",
    "        square[i, j] = solver.IntVar(1, n * n, 'square[%i,%i]' % (i, j))\n",
    "\n",
    "  # the magic sum\n",
    "  s = solver.IntVar(1, n * n * n, 's')\n",
    "\n",
    "  #\n",
    "  # constraints\n",
    "  #\n",
    "\n",
    "  # each cell must be assigned exactly one integer\n",
    "  for i in range_n:\n",
    "    for j in range_n:\n",
    "      solver.Add(solver.Sum([x[i, j, k] for k in range_N]) == 1)\n",
    "\n",
    "  # each integer must be assigned exactly to one cell\n",
    "  for k in range_N:\n",
    "    solver.Add(solver.Sum([x[i, j, k] for i in range_n for j in range_n]) == 1)\n",
    "\n",
    "  # # the sum in each row must be the magic sum\n",
    "  for i in range_n:\n",
    "    solver.Add(\n",
    "        solver.Sum([k * x[i, j, k] for j in range_n for k in range_N]) == s)\n",
    "\n",
    "  # # the sum in each column must be the magic sum\n",
    "  for j in range_n:\n",
    "    solver.Add(\n",
    "        solver.Sum([k * x[i, j, k] for i in range_n for k in range_N]) == s)\n",
    "\n",
    "  # # the sum in the diagonal must be the magic sum\n",
    "  solver.Add(\n",
    "      solver.Sum([k * x[i, i, k] for i in range_n for k in range_N]) == s)\n",
    "\n",
    "  # # the sum in the co-diagonal must be the magic sum\n",
    "  if range_n[0] == 1:\n",
    "    # for range_n = 1..n\n",
    "    solver.Add(\n",
    "        solver.Sum([k * x[i, n - i + 1, k]\n",
    "                    for i in range_n\n",
    "                    for k in range_N]) == s)\n",
    "  else:\n",
    "    # for range_n = 0..n-1\n",
    "    solver.Add(\n",
    "        solver.Sum([k * x[i, n - i - 1, k]\n",
    "                    for i in range_n\n",
    "                    for k in range_N]) == s)\n",
    "\n",
    "  # for output\n",
    "  if use_output_matrix == 1:\n",
    "    for i in range_n:\n",
    "      for j in range_n:\n",
    "        solver.Add(\n",
    "            square[i, j] == solver.Sum([k * x[i, j, k] for k in range_N]))\n",
    "\n",
    "  #\n",
    "  # solution and search\n",
    "  #\n",
    "  solver.Solve()\n",
    "\n",
    "  print()\n",
    "\n",
    "  print('s: ', int(s.SolutionValue()))\n",
    "  if use_output_matrix == 1:\n",
    "    for i in range_n:\n",
    "      for j in range_n:\n",
    "        print(int(square[i, j].SolutionValue()), end=' ')\n",
    "      print()\n",
    "    print()\n",
    "  else:\n",
    "    for i in range_n:\n",
    "      for j in range_n:\n",
    "        print(\n",
    "            sum([int(k * x[i, j, k].SolutionValue()) for k in range_N]),\n",
    "            ' ',\n",
    "            end=' ')\n",
    "      print()\n",
    "\n",
    "  print('\\nx:')\n",
    "  for i in range_n:\n",
    "    for j in range_n:\n",
    "      for k in range_N:\n",
    "        print(int(x[i, j, k].SolutionValue()), end=' ')\n",
    "      print()\n",
    "\n",
    "  print()\n",
    "  print('walltime  :', solver.WallTime(), 'ms')\n",
    "  if sol == 'CBC':\n",
    "    print('iterations:', solver.Iterations())\n",
    "\n",
    "\n",
    "n = 3\n",
    "sol = 'CBC'\n",
    "use_output_matrix = 0\n",
    "if len(sys.argv) > 1:\n",
    "  n = int(sys.argv[1])\n",
    "\n",
    "if len(sys.argv) > 2:\n",
    "  sol = sys.argv[2]\n",
    "  if sol != 'GLPK' and sol != 'CBC':\n",
    "    print('Solver must be either GLPK or CBC')\n",
    "    sys.exit(1)\n",
    "\n",
    "if len(sys.argv) > 3:\n",
    "  use_output_matrix = int(sys.argv[3])\n",
    "\n",
    "main(n, sol, use_output_matrix)\n",
    "\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
